﻿using System;
using System.Threading.Tasks;
using Casamiel.API.Application;
using Casamiel.API.Application.Models.Store;
using Casamiel.API.Infrastructure;
using Casamiel.API.Infrastructure.Filters;
using Casamiel.Application;
using Casamiel.Common.Extensions;
using Casamiel.Domain.Request;
using Casamiel.Domain.Response;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using NLog;

// For more information on enabling Web API for empty projects, visit https://go.microsoft.com/fwlink/?LinkID=397860

namespace Casamiel.API.Controllers.V2
{
    /// <summary>
    /// Shipping address controller.
    /// </summary>
    [Produces("application/json")]
    [ApiVersion("2.0")]
    [Route("api/v{api-version:apiVersion}/ShippingAddress")]
    [TypeFilterAttribute(typeof(CheckTokenAttribute))]
    [Authorize]
    [ApiController]
    public class ShippingAddressController : Controller
    {
        private readonly NLog.ILogger logger = LogManager.GetLogger("OrderService");
        private readonly IUserLogService _userLog;
        private readonly IStoreApiService _storeApiService;
        private readonly IStoreService _storeService;
        private readonly ICasaMielSession _session;

        /// <summary>
        /// 
        /// </summary>
        /// <param name="userLogService"></param>
        /// <param name="storeService"></param>
        /// <param name="storeApiServicem"></param>
        /// <param name="casaMielSession"></param>
        public ShippingAddressController(IUserLogService userLogService, IStoreService storeService, IStoreApiService storeApiServicem, ICasaMielSession casaMielSession)
        {
            this._userLog = userLogService;
            this._storeService = storeService;
            this._storeApiService = storeApiServicem;
            this._session = casaMielSession;
        }

        /// <summary>
        /// 我的收货地址
        /// </summary>
        /// <returns>The my address list.</returns>
        /// <param name="token">.</param>
        [HttpPost]
        [Route("[action]")]
        public async Task<IActionResult> GetMyAddressList([FromHeader(Name = "u-token")] string token)
        {
            var mobile = MemberHelper.GetMobile(token);
            var list = await _storeApiService.GetList(mobile).ConfigureAwait(false);
            if (list != null) {
                return Ok(new { code = 0, content = list, total = list.Count });
            }

            return Ok(new { code = 0, content = list, total = 0 });
        }
        /// <summary>
        /// 我的配送收货地址列表
        /// </summary>
        /// <returns>The list by degree.</returns>
        /// <param name="data"></param>
        /// <param name="token">Token.</param>
        /// <remarks>{"storeId":XX}</remarks>
        [HttpPost]
        [Route("[action]")]
        public async Task<IActionResult> GetListByDegree([FromBody]GetListByStoreIdReq data, [FromHeader(Name = "u-token")] string token)
        {
            if (data == null) {
                throw new ArgumentNullException(nameof(data));
            }

            var mobile = MemberHelper.GetMobile(token);
            var list = await _storeApiService.GetListByDegree(mobile, data.StoreId).ConfigureAwait(false);

            return Ok(new { code = 0, content = list });
        }

        /// <summary>
        ///我的配送收货地址新增修改
        /// </summary>
        /// <returns>The save.</returns>
        /// <param name="data">Data.</param>
        /// <param name="token">Token.</param>
        [HttpPost]
        [Route("[action]")]
        public async Task<BaseResult<AddressBaseRsp>> AddressSave([FromBody] AddressSaveReq data, [FromHeader(Name = "u-token")] string token)
        {
            if (data == null) {
                throw new ArgumentNullException(nameof(data));
            }

            var mobile = MemberHelper.GetMobile(token);
            data.Mobile = mobile;
            logger.Trace($"AddressSave:{JsonConvert.SerializeObject(data)}");
            var rsp = await _storeApiService.Save(data).ConfigureAwait(false);
            logger.Trace(rsp);
            return rsp;
            //var dynamicdata = JsonConvert.DeserializeObject<JObject>(rsp);
            //var ResultNo = dynamicdata["ResultNo"].ToString();

            //if (ResultNo == "00000000")
            //{
            //    var entity = JsonConvert.DeserializeObject<Address_BaseRsp>(dynamicdata["Data"].ToString());
            //    return Ok(new { code = 0, content = entity,msg="操作成功"});

            //}
            //else if (ResultNo == "01030010")//01030010
            //{
            //    return Ok(new { code = -29, msg = dynamicdata["ResultRemark"].ToString() });
            //}
            //return Ok(new { code = 999, msg = dynamicdata["ResultRemark"].ToString() });
        }
        /// <summary>
        /// Gets the detail by identifier.
        /// </summary>
        /// <returns>The detail by identifier.</returns>
        /// <param name="data">Data.</param>
        /// <param name="token">Token.</param>
        /// <remarks>
        /// {"id":1}
        /// </remarks>
        [HttpPost]
        [Route("[action]")]
        public async Task<IActionResult> GetDetailById([FromBody] JObject data, [FromHeader(Name = "u-token")] string token)
        {
            if (data == null) {
                throw new ArgumentNullException(nameof(data));
            }

            var mobile = MemberHelper.GetMobile(token);
            var entity = await _storeApiService.GetBase(data["id"].ToInt32(0), mobile).ConfigureAwait(false);
            if (entity != null && entity.ConsigneeId > 0) {
                return Ok(new { code = 0, content = entity, msg = "" });
            }
            //return Ok(new { code = 0, pageindex = pageindex, pagesize = pagesize, total = total, content = entity });
            return Ok(new { code = -28, content = entity, msg = "收货地址不存在" });
        }
        /// <summary>
        /// Removes the by identifier.
        /// </summary>
        /// <returns>The by identifier.</returns>
        /// <param name="data">Data.</param>
        /// <param name="token">Token.</param>
        /// <remarks>
        /// {"id":1}
        /// </remarks>
        [HttpPost]
        [Route("[action]")]
        public async Task<IActionResult> RemoveById([FromBody] JObject data, [FromHeader(Name = "u-token")] string token)
        {
            if (data == null) {
                throw new ArgumentNullException(nameof(data));
            }

            var mobile = MemberHelper.GetMobile(token);
            var rsp = await _storeApiService.DeleteAddress(data["id"].ToInt32(0), mobile).ConfigureAwait(false);
            var dynamicdata = JsonConvert.DeserializeObject<JObject>(rsp);
            var ResultNo = dynamicdata["ResultNo"].ToString();
            if (ResultNo == "00000000") {
                return Ok(new { code = 0, content = "" });
            }

            return Ok(new { code = 999, msg = dynamicdata["Remark"].ToString() });
        }
        /// <summary>
        ///新增收货地址
        /// </summary>
        /// <returns>The save.</returns>
        /// <param name="data">Data.</param>
        /// <param name="token">Token.</param>
        [HttpPost]
        [Route("[action]")]
        public async Task<BaseResult<string>> Save([FromBody] AddressSaveReq data, [FromHeader(Name = "u-token")] string token)
        {
            if (data == null) {
                throw new ArgumentNullException(nameof(data));
            }

            var mobile = MemberHelper.GetMobile(token);
            data.Mobile = mobile;
            var rsp = await _storeApiService.SaveAddress(data).ConfigureAwait(false);
            return rsp;
            //var dynamicdata = JsonConvert.DeserializeObject<JObject>(rsp);
            //var ResultNo = dynamicdata["ResultNo"].ToString();
            //if (ResultNo == "00000000")
            //{
            //    return Ok(new { code = 0, content = "" });
            //}
            //else if (ResultNo == "01030008")
            //{
            //    return Ok(new { code = -29, msg = dynamicdata["Remark"].ToString() });
            //}
            //return Ok(new { code = 999, msg = dynamicdata["Remark"].ToString() });
        }
        /// <summary>
        /// 修改收货地址
        /// </summary>
        /// <returns>The modify.</returns>
        [HttpPost]
        [Route("[action]")]
        public async Task<BaseResult<string>> Modify([FromBody] AddressSaveReq data, [FromHeader(Name = "u-token")] string token)
        {
            var mobile = MemberHelper.GetMobile(token);
            var rsp = await _storeApiService.SaveAddress(data).ConfigureAwait(false);
            return rsp;
            //var dynamicdata = JsonConvert.DeserializeObject<JObject>(rsp);
            //var ResultNo = dynamicdata["ResultNo"].ToString();
            //if (ResultNo == "00000000")
            //{
            //    return Ok(new { code = 0, content = "" });
            //}

            //return Ok(new { code = 999, msg = dynamicdata["Remark"].ToString() });
        }

        /// <summary>
        /// 设置默认收货地址
        /// </summary>
        /// <returns>The default.</returns>
        /// <param name="data">Data.</param>
        /// <param name="token">Token.</param>
        /// <remarks>
        /// {"id":1}
        /// </remarks>
        [HttpPost]
        [Route("[action]")]
        public async Task<IActionResult> SetDefault([FromBody] JObject data, [FromHeader(Name = "u-token")] string token)
        {
            if (data == null) {
                throw new ArgumentNullException(nameof(data));
            }

            var mobile = MemberHelper.GetMobile(token);
            var rsp = await _storeApiService.SetAddressDefault(data["id"].ToInt32(0), mobile).ConfigureAwait(false);
            var dynamicdata = JsonConvert.DeserializeObject<JObject>(rsp);
            var ResultNo = dynamicdata["ResultNo"].ToString();
            if (ResultNo == "00000000") {
                return Ok(new { code = 0, content = "" });
            }

            return Ok(new { code = 999, msg = dynamicdata["Remark"].ToString() });
        }
    }
}
